<template>
  <main-layout :username="username" :unread-count="unreadCount">
  <div>

        <!-- 主内容区 -->

          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>控制台</el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 页面标题和时间 -->
          <div class="page-header">
            <h2>控制台</h2>
            <p>{{ currentDateTime }}</p>
          </div>

          <!-- 数据统计卡片 -->
          <div class="stats-cards">
            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-info">
                  <p class="stat-label">今日产量(kg)</p>
                  <h3 class="stat-value">{{ todayProduction }}</h3>
                  <p class="stat-change positive"><i class="el-icon-arrow-up"></i> 8.2%</p>
                </div>
                <div class="stat-icon green-bg">
                  <i class="el-icon-crop"></i>
                </div>
              </div>
            </el-card>

            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-info">
                  <p class="stat-label">设备运行率</p>
                  <h3 class="stat-value">96.8%</h3>
                  <p class="stat-change positive"><i class="el-icon-arrow-up"></i> 1.5%</p>
                </div>
                <div class="stat-icon blue-bg">
                  <i class="el-icon-machine"></i>
                </div>
              </div>
            </el-card>

            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-info">
                  <p class="stat-label">今日订单</p>
                  <h3 class="stat-value">24</h3>
                  <p class="stat-change negative"><i class="el-icon-arrow-down"></i> 3.1%</p>
                </div>
                <div class="stat-icon purple-bg">
                  <i class="el-icon-document"></i>
                </div>
              </div>
            </el-card>

            <el-card class="stat-card" shadow="hover">
              <div class="stat-content">
                <div class="stat-info">
                  <p class="stat-label">异常次数</p>
                  <h3 class="stat-value">{{ exceptionCount }}</h3>
                  <p class="stat-change positive"><i class="el-icon-arrow-down"></i> 50%</p>
                </div>
                <div class="stat-icon orange-bg">
                  <i class="el-icon-warning"></i>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 图表区域 -->
          <div class="charts-container">
            <el-card class="chart-card" shadow="hover">
              <div slot="header">
                <h3>产量趋势 (近7天)</h3>
                <el-button icon="el-icon-refresh" size="mini" @click="refreshProductionChart"></el-button>
              </div>
              <div class="chart-content">
                <canvas id="productionChart"></canvas>
              </div>
            </el-card>

            <el-card class="chart-card" shadow="hover">
              <div slot="header">
                <h3>设备状态分布</h3>
                <el-button icon="el-icon-refresh" size="mini" @click="refreshEquipmentChart"></el-button>
              </div>
              <div class="chart-content">
                <canvas id="equipmentChart"></canvas>
              </div>
            </el-card>
          </div>

          <!-- 快捷操作 -->
          <div class="quick-actions">
            <h3>快捷操作</h3>
            <div class="action-buttons">
              <el-button type="primary" icon="el-icon-plus" @click="handleNewProduction">
                新增生产记录
              </el-button>
              <el-button type="success" icon="el-icon-refresh" @click="handleEquipmentCheck">
                设备巡检
              </el-button>
              <el-button type="warning" icon="el-icon-shopping-cart" @click="handleNewOrder">
                新增订单
              </el-button>
              <el-button type="info" icon="el-icon-download" @click="handleExport">
                数据导出
              </el-button>
              <el-button type="danger" icon="el-icon-warning" @click="handleException" :disabled="exceptionCount === 0">
                处理异常 <el-badge :value="exceptionCount" class="exception-badge"></el-badge>
              </el-button>
            </div>
          </div>

          <!-- 最近生产记录 -->
          <el-card class="recent-records" shadow="hover">
            <div slot="header">
              <h3>最近生产记录</h3>
              <el-button type="text" @click="viewAllRecords">查看全部</el-button>
            </div>
            <el-table :data="tableData" stripe style="width: 100%" v-loading="tableLoading">
              <el-table-column prop="date" label="日期" width="180"></el-table-column>
              <el-table-column prop="product" label="产品名称" width="180"></el-table-column>
              <el-table-column prop="quantity" label="数量(kg)" width="120"></el-table-column>
              <el-table-column prop="operator" label="操作员" width="140"></el-table-column>
              <el-table-column prop="status" label="状态">
                <template slot-scope="scope">
                  <el-tag
                      :type="scope.row.status === '完成' ? 'success' :
                           scope.row.status === '进行中' ? 'info' : 'warning'"
                  >
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="action" label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="viewRecordDetail(scope.row)">查看</el-button>
                  <el-button size="mini" type="text" @click="editRecord(scope.row)">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                  background
                  layout="total, prev, pager, next, sizes"
                  :total="totalRecords"
                  :page-sizes="[5, 10, 20]"
                  :page-size="pageSize"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              ></el-pagination>
            </div>
          </el-card>

  </div>
  </main-layout>
</template>

<script>
import axios from "axios";
import Chart from 'chart.js';
import MainLayout from "@/components/layout/MainLayout.vue";

export default {
  components: {MainLayout},
  data() {
    return {
      // 基础信息
      username: '管理员',
      currentDateTime: '',
      isCollapse: false,
      unreadCount: 3,

      // 数据统计
      todayProduction: '1,286',
      exceptionCount: 2,

      // 表格数据
      tableData: [
        { date: '2023-06-15', product: '碧螺春', quantity: 128, operator: '张三', status: '完成' },
        { date: '2023-06-14', product: '龙井', quantity: 95, operator: '李四', status: '完成' },
        { date: '2023-06-14', product: '铁观音', quantity: 156, operator: '王五', status: '完成' },
        { date: '2023-06-13', product: '大红袍', quantity: 87, operator: '赵六', status: '完成' },
        { date: '2023-06-12', product: '碧螺春', quantity: 112, operator: '张三', status: '进行中' }
      ],
      tableLoading: false,
      totalRecords: 50,
      pageSize: 5,

      // 图表实例
      productionChart: null,
      equipmentChart: null
    }
  },
  methods: {
    // 侧边栏折叠
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },

    // 分页方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadProductionRecords(); // 重新加载数据
    },
    handleCurrentChange(val) {
      this.loadProductionRecords(val); // 加载指定页数据
    },

    // 加载生产记录
    loadProductionRecords() {
      this.tableLoading = true;
      // 模拟API请求
      setTimeout(() => {
        this.tableLoading = false;
      }, 500);
    },

    // 快捷操作
    handleNewProduction() {
      this.$router.push('/production/add'); // 跳转到新增生产记录页
    },
    handleEquipmentCheck() {
      this.$router.push('/equipment/check'); // 跳转到设备巡检页
    },
    handleNewOrder() {
      this.$router.push('/order/add'); // 跳转到新增订单页
    },
    handleExport() {
      this.$confirm('确定要导出今日生产数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 调用导出API
        this.$message.success('数据导出成功');
      }).catch(() => {});
    },
    handleException() {
      this.$router.push('/exception'); // 跳转到异常处理页
    },
    viewAllRecords() {
      this.$router.push('/production/records'); // 跳转到全部记录页
    },

    // 记录操作
    viewRecordDetail(row) {
      this.$router.push(`/production/detail/${row.product}`); // 查看详情
    },
    editRecord(row) {
      this.$router.push(`/production/edit/${row.product}`); // 编辑记录
    },

    // 通知处理
    handleNotice() {
      this.$notify({
        title: '通知',
        message: '您有3条未处理的设备维护提醒',
        type: 'warning',
        duration: 3000
      });
    },

    // 图表初始化与刷新
    initCharts() {
      this.initProductionChart();
      this.initEquipmentChart();
    },
    initProductionChart() {
      const productionCtx = document.getElementById('productionChart').getContext('2d');
      this.productionChart = new Chart(productionCtx, {
        type: 'line',
        data: {
          labels: ['6/9', '6/10', '6/11', '6/12', '6/13', '6/14', '6/15'],
          datasets: [{
            label: '产量(kg)',
            data: [980, 1050, 1120, 990, 1180, 1210, 1286],
            borderColor: '#4caf50',
            backgroundColor: 'rgba(76, 175, 80, 0.1)',
            tension: 0.3,
            fill: true
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: { legend: { display: false } },
          scales: { y: { beginAtZero: true } }
        }
      });
    },
    initEquipmentChart() {
      const equipmentCtx = document.getElementById('equipmentChart').getContext('2d');
      this.equipmentChart = new Chart(equipmentCtx, {
        type: 'doughnut',
        data: {
          labels: ['运行中', '闲置', '维护中', '故障'],
          datasets: [{
            data: [65, 20, 10, 5],
            backgroundColor: ['#4caf50', '#8bc34a', '#ffc107', '#f44336']
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: { legend: { position: 'right' } }
        }
      });
    },
    refreshProductionChart() {
      // 模拟数据刷新
      this.productionChart.data.datasets[0].data = [980, 1050, 1120, 990, 1180, 1210, Math.floor(1286 * (1 + Math.random() * 0.1))];
      this.productionChart.update();
      this.$message.success('产量图表已刷新');
    },
    refreshEquipmentChart() {
      // 模拟设备状态刷新
      this.equipmentChart.update();
      this.$message.success('设备状态图表已刷新');
    },

    // 更新时间
    updateDateTime() {
      const now = new Date();
      this.currentDateTime = now.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    // 加载数据
    loadSystemData() {
      axios({
        method: 'get',
        url: '/api/teaSystem/dashboard',
        params: { username: this.username }
      }).then(({ data }) => {
        if (data.code === 200) {
          this.todayProduction = data.todayProduction;
          this.exceptionCount = data.exceptionCount;
          this.unreadCount = data.unreadCount;
        } else {
          this.$message.error('数据加载失败: ' + data.msg);
        }
      }).catch(error => {
        this.$message.error('网络错误，请稍后重试');
        console.error('数据加载失败:', error);
      });
    }
  },
  mounted() {
    // 初始化时间并定时更新
    this.updateDateTime();
    this.timeTimer = setInterval(() => this.updateDateTime(), 1000);

    // 初始化图表和数据
    this.initCharts();
    this.loadSystemData();
    this.loadProductionRecords();
  },
  beforeDestroy() {
    // 清理资源
    clearInterval(this.timeTimer);
    if (this.productionChart) this.productionChart.destroy();
    if (this.equipmentChart) this.equipmentChart.destroy();
  }
}
</script>

<style>
.el-header {
  background-color: #85DB34;
  color: #2e7d32;
  line-height: 60px;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h1 {
  margin: 0;
  font-size: 1.5rem;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.notification-badge {
  vertical-align: middle;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-avatar {
  background-color: #2e7d32;
  cursor: pointer;
}

.el-aside {
  background-color: #f0f9e8;
  position: relative;
}

.aside-toggle {
  text-align: center;
  padding: 10px 0;
  cursor: pointer;
  color: #2e7d32;
}

.el-main {
  background-color: #f9f9f9;
  padding: 20px;
  overflow-y: auto;
}

.breadcrumb {
  margin-bottom: 15px;
  font-size: 0.9rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #2e7d32;
}

/* 统计卡片 */
.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 200px;
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-3px);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 15px;
}

.stat-info {
  flex: 1;
}

.stat-label {
  color: #666;
  margin: 0 0 5px 0;
  font-size: 0.9rem;
}

.stat-value {
  margin: 0 0 5px 0;
  font-size: 1.5rem;
  font-weight: bold;
  color: #333;
}

.stat-change {
  margin: 0;
  font-size: 0.8rem;
}

.positive {
  color: #4caf50;
}

.negative {
  color: #f44336;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1.2rem;
}

.green-bg {
  background-color: rgba(76, 175, 80, 0.8);
}

.blue-bg {
  background-color: rgba(33, 150, 243, 0.8);
}

.purple-bg {
  background-color: rgba(156, 39, 176, 0.8);
}

.orange-bg {
  background-color: rgba(255, 152, 0, 0.8);
}

/* 图表容器 */
.charts-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  height: 300px;
}

.chart-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-card .el-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
}

.chart-content {
  flex: 1;
  position: relative;
}

/* 快捷操作 */
.quick-actions {
  margin-bottom: 20px;
}

.quick-actions h3 {
  margin-bottom: 10px;
  color: #2e7d32;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.exception-badge {
  position: relative;
  top: -10px;
  right: 10px;
}

/* 最近记录 */
.recent-records {
  margin-top: 20px;
}

.recent-records .el-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .charts-container {
    height: 250px;
  }
}

@media (max-width: 768px) {
  .charts-container {
    flex-direction: column;
    height: auto;
  }

  .chart-card {
    height: 300px;
    margin-bottom: 20px;
  }

  .stats-cards {
    flex-direction: column;
  }

  .stat-card {
    width: 100%;
  }
}
</style>